const express = require("express");
const app = express();
const bodyParser = require("body-parser");
//获取客户端 ip 地址
app.use(function (request, response, next) {
  // access 访问进入  control 控制  allow 允许  origin 源
  response.setHeader("Access-Control-Allow-Origin", "*"); //允许跨域请求  默认只允许 GET 和 POST
  response.setHeader("Access-Control-Allow-Methods", "*"); //允许各种请求方式进行跨域请求  PUT  PATCH DELETE
  response.setHeader("Access-Control-Allow-Headers", "*"); //该响应头 允许客户端可以设置『自定义』请求头
  response.setHeader("Access-Control-Expose-Headers", "*"); //暴露响应头信息
  response.setHeader("Access-Control-Max-Age", 120); // 设置有效时间

  next();
});

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));

// parse application/json
app.use(bodyParser.json());

//创建路由规则    http://127.0.0.1:8080
app.all("/server", (req, res) => {
  // send  text/html
  // res.end(`console.log(123)`);
  // res.end(`div.innerHTML = 123`);
  // res.end(`document.body.style.background = 'rgb(20, 20, 80)'`)
  //准备数据
  // let color = 'rgb(30,30,100)';
  // res.end(`cb('${color}')`);
  //准备数据
  let book = {
    title: '西游记',
    price: 19.9,
    author: '吴承恩'
  };
  let fn = req.query.fn;
  //响应结果
  res.end(`${fn}(${JSON.stringify(book)})`)
});

app.all('/page', (req, res) => {
  //读取 home.html 的文件内容
  let html = require('fs').readFileSync('../2-跨域/0-同源策略/home.html');
  res.end(html);
})

//创建路由规则
app.all("/server/:id", (req, res) => {
  //获取 id 参数
  // console.log(req.params.id);
  //设置响应头    访问    控制    允许    源
  // res.setHeader('access-control-allow-origin', '*');
  // res.setHeader('access-control-allow-origin', 'http://127.0.0.1:5500');

  res.send("HELLO AJAX 123456789");
});

//检查手机号
app.all("/check-phone", (req, res) => {
  //响应 JSON
  res.json({
    msg: "手机号已经存在",
    code: 1001,
  });
});

//添加 search 路由规则
app.all("/search", (req, res) => {
  //延迟 3s 响应结果
  setTimeout(() => {
    res.send("搜索结果");
  }, 3000);
});

app.post("/post-test", (req, res) => {
  require("fs").writeFileSync(
    "./access.log",
    JSON.stringify(req.body) + "\r\n",
    { flag: "a" }
  );
  res.send("OK");
});

app.listen(8080, () => {
  console.log("服务已经启动....");
});
